import {
  CanActivate,
  ExecutionContext,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { JwtService } from '@nestjs/jwt';
import { Request } from 'express';

@Injectable()
export class JwtAuthGuard implements CanActivate {
   // 定义公开路由的正则表达式数组
  private publicRoutes: RegExp[] = [
    /^\/api\/auth\/login$/, // 精确匹配 /api/auth/login
    /^\/api\/city/,        // 匹配所有以 /api/city 开头的路由
    /^\/api\/user\//,      // 匹配所有以 /api/user/ 开头的路由
    /^\/api\//
  ];
   
  constructor(private readonly jwtService: JwtService) {}

  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest<Request>();

    // 当前请求的 path
    const path = request.route.path;

    // 检查路径是否匹配公开路由的正则表达式
    for (const route of this.publicRoutes) {
      if (route.test(path)) {
        return true; // 如果匹配，直接放行
      }
    }

    


    // 否则校验 JWT
    const authHeader = request.headers['authorization'];
    if (!authHeader) {
      throw new UnauthorizedException('未提供认证信息');
    }

    const token = authHeader.replace('Bearer ', '');
    try {
      request.user = this.jwtService.verify(token); // 把解码后的用户放到 request 上
      return true;
    } catch (e) {
      throw new UnauthorizedException('无效的 Token');
    }
  }
}
